package com.lagou.edu.spring;

import com.lagou.edu.annotation.Autowired;
import com.lagou.edu.annotation.Service;
import com.lagou.edu.annotation.Transactional;
import com.lagou.edu.utils.ClassUtil;
import com.lagou.edu.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 自定义注解配置类
 * 用于检测自定义注解、创建bean、读取bean
 * @auther: guangjun.ma
 * @date: 2020-3-31 18:43
 * @version: 1.0
 */

public class MyAnnotationXmlClassPathApplication {

    //扫描的包名
    private String packageName;
    //bean对象classinfo池
    private static ConcurrentHashMap<String,Class<?>> beans = null;
    //bean对象单例池
    private static ConcurrentHashMap<String,Object> beanSingleFactory = null;


    //初始化
    public MyAnnotationXmlClassPathApplication(String packageName) {
        this.packageName = packageName;
        beans = new ConcurrentHashMap<String ,Class<?>>();
        beanSingleFactory = new ConcurrentHashMap<String,Object>();
        initBean();//初始化bean
    }

    /**
     * 初始化bean
     */
    private void initBean() {
        //1、获得指定包下的所有的class类
        List<Class<?>> classes = ClassUtil.getClasses(packageName);

        //2、查找并处理所有自定义注解的类  @Service
        handleClassAnnotionForService(classes);

        //3、查找并处理所有自定义注解的方法 @Autowired
        handleClassAnnotionForAutowired(classes);

        //4、查找并处理所有自定义注解的方法 @Transactional注解
        handleClassAnnotionForTransactional(classes);

    }



    /**
     * 查找带有自定义注解类 @Service ，并处理完放入到对象池中
     * @param classes
     * @return
     * @auther: guangjun.ma
     * @date: 2020-3-31 19:43
     * @version: 1.0
     */
    private void handleClassAnnotionForService(List<Class<?>> classes) {
        for (Class<?> classInfo : classes){
            //@Service自定义注解
            Service annocation = classInfo.getAnnotation(Service.class);
            if (null != annocation){
                String beanId = getBeanName(annocation,classInfo);
                //放入对象池beans
                beans.put(beanId,classInfo);
            }
        }
    }

    /**
     * 处理@Autowired自定义注解
     *
     * @param classes
     * @return
     * @auther: guangjun.ma
     * @date: 2020-3-31 19:44
     * @version: 1.0
     */
    private void handleClassAnnotionForAutowired(List<Class<?>> classes) {
        try{
            //1、获得所有的class
            for (Class<?> classInfo : classes){
                Field[] fields = classInfo.getDeclaredFields();
                for (Field field : fields){
                    //2、查找@Autowired标识的属性
                    Autowired annotation = field.getAnnotation(Autowired.class);
                    if (null == annotation){
                        continue;
                    }

                    //3、获得当前bean
                    String beanName = "";
                    Set<Map.Entry<String, Class<?>>> entrySet = beans.entrySet();
                    for (Map.Entry<String, Class<?>> entry : entrySet){
                        if (entry.getValue().equals(classInfo)){
                            beanName = entry.getKey();
                            break;
                        }
                    }
                    if (beanName.isEmpty()){continue;}
                    //获得当前类
                    Object bean = getBean(beanName);
                    String fieldName = field.getName();
                    //4、获得属性对应的bean，即refbean  这里用属性名查找对象
                    Object refBean = getBean(fieldName);
                    if (null == refBean){continue;}
                    Method[] methods = classInfo.getDeclaredMethods();
                    for(Method method : methods){
                        //5、注入属性bean
                        if (method.getName().equalsIgnoreCase("set" + toUpperCaseFirstOne(fieldName))){
                            field.setAccessible(true);
                            method.invoke(bean,refBean);
                            //6、将主对象重新放入到对象池
                            beanSingleFactory.put(beanName,bean);
                        }
                    }
                }
            }
        }catch (Exception e){
           e.printStackTrace();
        }
    }


    /**
     * 查找并处理所有自定义注解的方法 @Transactional注解
     * @param classes
     * @return
     * @auther: guangjun.ma
     * @date: 2020-3-31 23:39
     * @version: 1.0
     */
    private void handleClassAnnotionForTransactional(List<Class<?>> classes) {
        try {
            for (Class<?> classInfo : classes){
                //@Transactional 自定义注解
                Service serviceAnnocation = classInfo.getAnnotation(Service.class);
                Transactional transactionAlannocation = classInfo.getAnnotation(Transactional.class);
                if (null != transactionAlannocation){
                    //1、获得原对象target
                    String beanId = getBeanName(serviceAnnocation,classInfo);
                    getBean(beanId);
                    Object target = beanSingleFactory.get(beanId);

                    //2、获得代理对象 、事务管理器
                    beans.get("transactionManager");
                    TransactionManager transactionManager = (TransactionManager)beanSingleFactory.get("transactionManager");
                    Object retObj = null;
                    Class<?>[] interfaces = classInfo.getInterfaces();
                    if (interfaces.length != 0){//2.1 若被代理类存在接口则使用jdk代理

                        // 获取代理对象
                        retObj =  Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
                                new InvocationHandler() {
                                    @Override
                                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                        Object result = null;
                                        try{
                                            // 开启事务(关闭事务的自动提交)
                                            transactionManager.beginTransaction();
                                            //逻辑处理
                                            result = method.invoke(target,args);
                                            // 提交事务
                                            transactionManager.commit();
                                        }catch (Exception e) {
                                            e.printStackTrace();
                                            // 回滚事务
                                            transactionManager.rollback();
                                            // 抛出异常便于上层servlet捕获
                                            throw e;
                                        }
                                        return result;
                                    }
                                });
                    }else {//2.2 若被代理类不存在接口则使用cglib代理
                        retObj = Enhancer.create(target.getClass(), new MethodInterceptor() {
                            @Override
                            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                                Object result = null;
                                try{
                                    // 开启事务(关闭事务的自动提交)
                                    transactionManager.beginTransaction();
                                    //逻辑处理
                                    result = method.invoke(target,objects);
                                    // 提交事务
                                    transactionManager.commit();
                                }catch (Exception e) {
                                    e.printStackTrace();
                                    // 回滚事务
                                    transactionManager.rollback();
                                    // 抛出异常便于上层servlet捕获
                                    throw e;
                                }
                                return result;
                            }
                        });
                    }
                    //代理对象放入
                    beanSingleFactory.put(beanId,retObj);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获得beanNanme
     * 这里包括处理注解默认值的处理
     * 
     * @param annocation
     * @param classInfo
     * @return
     * @auther: guangjun.ma
     * @date: 2020-3-31 19:36
     * @version: 1.0
     */
    private String getBeanName(Service annocation, Class<?> classInfo) {
        String defaultValue = annocation.value();
        //1、bean未指定value，默认值处理
        if (null == defaultValue || defaultValue.isEmpty() || defaultValue.trim().isEmpty()){
            //获取简单类名
            String className = classInfo.getSimpleName();
            //类字母小写转化
            return toLowerCaseFirstOne(className);
        }
        //2、bean指定value处理
        return defaultValue.trim();
    }


    /**
     * 类首字母小写转化  User --> user
     * @param s
     * @return
     * @auther: guangjun.ma
     * @date: 2020-3-31 19:19
     * @version: 1.0
     */
    private String toLowerCaseFirstOne(String s) {
        StringBuilder stringBuilder = new StringBuilder();
        if (Character.isLowerCase(s.charAt(0))){
            return s;
        }else {
            return stringBuilder.append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
        }
    }

    /**
     * 首字母大写
     * user -- > User
     * @param s
     * @return
     * @auther: guangjun.ma
     * @date: 2020-3-31 21:04
     * @version: 1.0
     */
    private String toUpperCaseFirstOne(String s) {
        StringBuilder stringBuilder = new StringBuilder();
        if (Character.isUpperCase(s.charAt(0))){
            return s;
        }else {
            return stringBuilder.append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
        }
    }

    /**
     * 从容器中获得bean对象
     * @param beanId
     * @return
     * @throws Exception
     * @auther: guangjun.ma
     * @date: 2020-3-31 19:22
     * @version: 1.0
     */
    public Object getBean(String beanId){
        try {
            Object o = beanSingleFactory.get(beanId);
            if (null !=  o){
                return  o;
            }

            if (null ==  beanId || beanId.isEmpty()){
                throw new Exception("bean id is empty！");
            }
            Class<?> classInfo = beans.get(beanId);
            if (null == classInfo){
                throw  new Exception("class not found!");
            }
            //反射获得bean实例
            Object retObject = newInstacne(classInfo);
            //放入对象单例池
            beanSingleFactory.put(beanId,retObject);
            return retObject;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 反射获得bean实例
     * @param classInfo
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @auther: guangjun.ma
     * @date: 2020-3-31 19:23
     * @version: 1.0
     */
    private Object newInstacne(Class<?> classInfo) throws IllegalAccessException, InstantiationException {
        return classInfo.newInstance();
    }


}
